package com.hwadee.service.impl;

import com.hwadee.mapper.PermissionMapper;
import com.hwadee.mapper.RoleMapper;
import com.hwadee.pojo.Role;
import com.hwadee.pojo.RoleWithPermissions;
import com.hwadee.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;


    @Autowired
    private PermissionMapper permissionMapper;
    //获取系统中所有角色信息
    @Override
    public List<Role> getAllRoles() {
        return roleMapper.getAllRoles();
    }
    //添加一个新角色（不包含权限绑定）
    @Override
    public int addRole(Role role) {
        roleMapper.insertRole(role);
        return role.getId();
    }
    //添加一个角色，并同时绑定权限
    @Override
    public int addRoleWithPermissions(RoleWithPermissions roleData) {
        // 先构建角色对象
        Role role = new Role();
        role.setName(roleData.getName());
        role.setDescription(roleData.getDescription());
        // 插入角色表
        int result = roleMapper.insertRole(role);
        Integer roleId = role.getId(); // // 获取插入后的角色 ID（自增主键）
        // 插入角色权限关联记录
        for (Integer pid : roleData.getPermissionIds()) {
            permissionMapper.addRolePermission(roleId, pid);
        }

        return result;
    }
    //根据角色 ID 删除角色
    @Override
    public int deleteRoleById(Integer id) {
        return roleMapper.deleteRoleById(id);
    }
    //查询某个角色已绑定的所有权限 ID
    @Override
    public List<Integer> getPermissionIdsByRoleId(Integer roleId) {
        return roleMapper.getPermissionIdsByRoleId(roleId);
    }
    //修改角色基本信息及其权限绑定关系
    @Override
    public void updateRoleWithPermissions(Integer roleId, RoleWithPermissions roleData) {
        // 修改角色名称
        roleMapper.updateRoleName(roleId, roleData.getName());

        // 删除旧的权限绑定记录
        roleMapper.deleteRolePermissions(roleId);

        // 添加新权限
        List<Integer> permissionIds = roleData.getPermissionIds();
        if (permissionIds != null) {
            for (Integer permissionId : permissionIds) {
                roleMapper.addRolePermission(roleId, permissionId);
            }
        }
    }

}

